using System;
using System.Collections.Generic;
using System.Linq;
using Sustainalytics.Entities;
using Sustainalytics.Synchronization.Validation.Entities.CorporateGovernance;
using Sustainalytics.Synchronization.Validation.ValidationRules.Common;

namespace Sustainalytics.Synchronization.Validation.ValidationRules.CorporateGovernance
{
    public class GovernanceIndicatorScoreChangeRedRule : Rule<GovernanceValidationProfile>
    {
        private const int UpperScoreValue = 100;

        public override Severity Severity => Severity.Yellow;
        public override BusinessResearchProduct BusinessResearchProduct => BusinessResearchProduct.CorporateGovernance;
        public override string Code => "YR111";
        public override string InformationalMessage => "Indicators Score changes of +/-100 Points";

        public GovernanceIndicatorScoreChangeRedRule()
        {
            For(x => x.GovernanceIndicators).When(Validator).WithKey(x => x.CompanyId)
                .WithMessage("The company {0} #{1}# has score change of +/- 100 points for Governance Indicators");
        }

        private bool Validator(GovernanceValidationProfile validatedEntity, GovernanceValidationProfile referenceEntity)
        {
            var indicators = (List<GovernanceIndicator>)GetValue(validatedEntity);
            var referenceIndicators = (List<GovernanceIndicator>)GetValue(referenceEntity);

            if (indicators == null || referenceIndicators == null)
            {
                return false;
            }

            var triggerIndicators = (from indicator in indicators
                                     let referenceIndicator = referenceIndicators.FirstOrDefault(x => x.Number == indicator.Number)
                                     where referenceIndicator != null
                                        && !indicator.Number.Contains("CG.6")
                                        && Math.Abs(referenceIndicator.Score - indicator.Score) == UpperScoreValue
                                     select indicator.Number);

            if (!triggerIndicators.Any())
                return true;

            SetTriggersMessages(triggerIndicators);

            return false;
        }
    }
}